﻿<template>
    <full-screen-dialog
        :title="titleMap[mode]"
        v-model="visible"
        :width="1400"
        destroy-on-close
        :close-on-click-modal="false"
        :before-close="handleBeforeClose"
    >
        <el-form
            :model="entityObj"
            :rules="rules"
            :disabled="mode == 'Show'"
            ref="dialogForm"
            label-width="100px"
        >
            <!-- <el-steps
                :active="1"
                align-center
                finish-status="success"
                style="margin-top: -20px;margin-bottom: 18px;"
            >
                <el-step title="门店已下单" description />
                <el-step title="接单处理中" description />
                <el-step title="已完成" description />
            </el-steps>-->
            <div class="steps-view">
                <div class="steps-view-line">
                    <div class="w-119"></div>
                    <img :src="stepStatus.complete" class="w-32" />
                    <div class="steps-line-blue"></div>
                    <img :src="stepStatus.ing" class="w-24-4" />
                    <div class="steps-line-ash"></div>
                    <img :src="stepStatus.wait" class="w-24-4" />
                    <div class="steps-line-ash"></div>
                    <img :src="stepStatus.wait" class="w-24-4" />
                    <div class="steps-line-ash"></div>
                    <img :src="stepStatus.wait" class="w-32-4" />
                    <div class="w-119"></div>
                </div>
                <div class="steps-view-text">
                    <div class="steps-uning">1、门店已下单</div>
                    <div class="steps-ing">2、接单处理中</div>
                    <div class="steps-uning">3、物料已出库</div>
                    <div class="steps-uning">4、发货配送中</div>
                    <div class="steps-uning">5、已完成</div>
                </div>
            </div>

            <el-collapse v-model="activeNames" class="title">
                <div class="collapse-container">
                    <div class="collapse-header" @click="toggleCollapse">
                        <span>基础信息</span>
                        <div style="display: flex;align-items: center;">
                            <span class="expand-text">{{ isCollapsed ? '展开' : '收起' }}</span>
                            <img
                                v-if="isCollapsed"
                                class="icon-img"
                                src="https://oss.jtmckj.com/pc/images/pay/arrow-bt.png"
                            />
                            <img
                                v-else
                                class="icon-img"
                                src="https://oss.jtmckj.com/pc/images/pay/arrow-top.png"
                            />
                        </div>
                    </div>
                    <div v-show="!isCollapsed" class="collapse-content1">
                        <!-- 要展开/收起的内容 -->
                        <el-row>
                            <el-col :span="8">
                                <el-form-item
                                    label-width="120px"
                                    label="要货编号:"
                                >{{entityObj.applyOrderCode}}</el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item
                                    label-width="120px"
                                    label="要货时间:"
                                >{{entityObj.applyDate}}</el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item
                                    label-width="120px"
                                    label="期望到货时间:"
                                >{{entityObj.expectedDate}}</el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="8">
                                <el-form-item label-width="120px" label="要货单位:">
                                    <el-tooltip placement="top">
                                        <template #content>
                                            联系人: {{entityObj.realName}}
                                            <br />
                                            联系电话:{{entityObj.mobile}}
                                            <br />
                                            收货地址:{{entityObj.address}}
                                        </template>
                                        <span style="color: #308BF2;">{{entityObj.storeName}}</span>
                                    </el-tooltip>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label-width="120px" label="供货单位:">
                                    <el-tooltip placement="top">
                                        <template #content>
                                            联系人: {{entityObj.purchaseRealName}}
                                            <br />
                                            联系电话:{{entityObj.purchaseMobile}}
                                            <br />
                                            联系地址:{{entityObj.purchaseAddress}}
                                        </template>
                                        <span
                                            style="color: #308BF2;"
                                        >{{entityObj.purchaseUnityName}}</span>
                                    </el-tooltip>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item
                                    label-width="120px"
                                    label="申请人:"
                                >{{entityObj.applyName}}</el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="8">
                                <el-form-item
                                    label-width="120px"
                                    label="申请时间:"
                                >{{entityObj.applyDate}}</el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item
                                    label-width="120px"
                                    label="最后修改人:"
                                >{{entityObj.updateName}}</el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item
                                    label-width="120px"
                                    label="最后修改时间:"
                                >{{entityObj.updateTime}}</el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="8">
                                <el-form-item
                                    label-width="120px"
                                    label="附件:"
                                    v-if="entityObj.applyFile"
                                >
                                    <sc-upload-file
                                        v-model="entityObj.applyFile"
                                        :objName="'Supply/ApplyOrder'"
                                        draggable
                                        :uploadType="'OSS'"
                                        :bucketName="'jtmc'"
                                        disabled
                                        :limit="1"
                                    />
                                </el-form-item>
                                <el-form-item label-width="120px" label="附件:" v-else>无</el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="8">
                                <el-form-item label-width="120px" label="备注:">{{entityObj.remarks}}</el-form-item>
                            </el-col>
                        </el-row>
                    </div>
                </div>
                <div class="collapse-container">
                    <div class="collapse-header" @click="toggleCollapse2">
                        <span>要货清单</span>
                        <div style="display: flex;align-items: center;">
                            <span class="expand-text">{{ isCollapsed2 ? '展开' : '收起' }}</span>
                            <img
                                v-if="isCollapsed2"
                                class="icon-img"
                                src="https://oss.jtmckj.com/pc/images/pay/arrow-bt.png"
                            />
                            <img
                                v-else
                                class="icon-img"
                                src="https://oss.jtmckj.com/pc/images/pay/arrow-top.png"
                            />
                        </div>
                    </div>

                    <div v-show="!isCollapsed2" class="collapse-content">
                        <el-form inline label-width="49px" style="margin-top: 5px">
                            <el-form-item label="供应商" label-width="80px">
                                <el-select
                                    placeholder="---请选择供应商---"
                                    filterable
                                    v-model="queryList.supplierId"
                                    style="width: 160px"
                                >
                                    <el-option label="---请选择---" value />
                                    <el-option
                                        v-for="item in querySuppliers"
                                        :key="item.supplierId"
                                        :label="item.supplierName"
                                        :value="item.supplierId"
                                    />
                                </el-select>
                            </el-form-item>
                            <el-button
                                :icon="Search"
                                 
                                type="primary"
                                @click="handleSearch"
                            >查询</el-button>
                            <el-button :icon="Search" type="info" plain @click="resetSearch">重置</el-button>
                            <el-form inline label-width="49px" style="margin-top: 5px"></el-form>
                        </el-form>
                        <el-row>
                            <el-col :span="24" class="basic-table">
                                <!-- default-expand-all  -->
                                <el-table
                                    stripe
                                    :data="itemsData"
                                    :border="false"
                                    style="width: 100%;border-radius: 8px;"
                                    :row-class-name="setRowClass"
                                    @row-click="rowClickYh"
                                    default-expand-all
                                    class="subtable"
                                    show-summary
                                    :summary-method="getSummaries"
                                    @sort-change="handleSortChange"
                                    @selection-change="selectionChange"
                                >
                                    <el-table-column type="index" min-width="55" fixed />
                                    <!-- <el-table-column type="selection" width="50"></el-table-column> -->
                                    <el-table-column
                                        label="物料名称"
                                        prop="materialName"
                                        min-width="140"
                                        align="left"
                                    >
                                        <template #default="scope">
                                            <el-tooltip placement="top" style="width: 80%">
                                                <template #content>{{scope.row.materialCode}}</template>
                                                <div
                                                    v-if="scope.row.materialImages && scope.row.materialImages.length > 0"
                                                    style="color: #318cf2;"
                                                    @click="handlePreview(scope.row.materialImages)"
                                                >{{scope.row.materialName}}</div>
                                                <div v-else>{{scope.row.materialName}}</div>
                                            </el-tooltip>
                                        </template>
                                    </el-table-column>
                                    <el-table-column
                                        label="规格"
                                        prop="materialSpecs"
                                        min-width="120"
                                        align="center"
                                    />
                                    <el-table-column
                                        v-if="hasSomeFieldValue"
                                        label="材质"
                                        prop="materialQuality"
                                        min-width="120"
                                        align="center"
                                    ></el-table-column>
                                    <!-- <el-table-column
                                        label="单位"
                                        prop="unitName"
                                        min-width="70"
                                        align="center"
                                    />-->
                                    <el-table-column
                                        label="要货数量"
                                        prop="qty"
                                        min-width="120"
                                        align="center"
                                    >
                                        <template #default="scope">
                                            <el-input-number
                                                v-if="scope.row.applyOrderItemTempId>0"
                                                v-model="scope.row.qty"
                                                @blur="handleApplyQty(scope.row, scope.$index)"
                                                :step="1"
                                                :controls="false"
                                                style="width: 60%"
                                            />
                                            <span v-else> {{scope.row.qty}}</span>
                                            {{scope.row.unitName}}
                                        </template>
                                    </el-table-column>
                                    <el-table-column
                                        label="销售总额"
                                        prop="applyTotalAmount"
                                        min-width="100"
                                        align="center"
                                    />
                                    <el-table-column
                                        label="采购总额"
                                        prop="purchaseTotalAmount"
                                        min-width="100"
                                        align="center"
                                    />
                                    <el-table-column
                                        label="供应商"
                                        align="center"
                                        min-width="180"
                                        prop="supplierTotals"
                                        sortable="true"
                                        show-overflow-tooltip
                                    >
                                        <template #default="scope">
                                            <span style="color: #318cf2;">
                                                {{
                                                //getSupplierDesc(scope.row.purchases,scope.row.purchases[0].suppliers)
                                                scope.row.supplierTotals
                                                }}
                                            </span>
                                        </template>
                                    </el-table-column>
                                    <el-table-column
                                        label="备注"
                                        prop="remarks"
                                        align="center"
                                        min-width="80"
                                        show-overflow-tooltip
                                    />
                                    <el-table-column
                                        label="要货图片"
                                        prop="applyMaterialImages"
                                        align="center"
                                        min-width="80"
                                        show-overflow-tooltip
                                    >
                                        <template #default="scope">
                                            <div
                                                v-if="scope.row.applyMaterialImages && scope.row.applyMaterialImages?.length > 0"
                                                style="color: #318cf2;"
                                                @click="handlePreview(scope.row.applyMaterialImages)"
                                            >查看</div>
                                        </template>
                                    </el-table-column>
                                    <el-table-column
                                        label="赠送仓"
                                        prop="giveStockDesc"
                                        align="center"
                                        show-overflow-tooltip
                                        min-width="140"
                                    />
                                    <el-table-column label="是否有促销" align="center" min-width="140">
                                        <template
                                            #default="scope"
                                        >{{scope.row.isActivity?"有促销":"无"}}</template>
                                    </el-table-column>
                                    <el-table-column
                                        label="操作"
                                        fixed="right"
                                        align="center"
                                        min-width="140"
                                    >
                                        <template #default="scope">
                                            <el-button-group>
                                                <el-button
                                                    text
                                                    type="primary"
                                                    size="small"
                                                    @click="opReceive(scope.row, scope.$index)"
                                                >拆单</el-button>
                                                <el-button
                                                    text
                                                    type="primary"
                                                    size="small"
                                                    v-if="scope.row.applyOrderItemTempId>0"
                                                    @click="delOrder(scope.row, scope.$index)"
                                                >删除</el-button>
                                            </el-button-group>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </el-col>
                        </el-row>
                    </div>
                </div>
                <div
                    class="collapse-container"
                    v-if="entityObj.applyOrderItemTemps&&entityObj.applyOrderItemTemps.length>0"
                >
                    <div class="collapse-header" @click="toggleCollapse3">
                        <span>临时物料</span>
                        <div style="display: flex;align-items: center;">
                            <span class="expand-text">{{ isCollapsed3 ? '展开' : '收起' }}</span>
                            <img
                                v-if="isCollapsed3"
                                class="icon-img"
                                src="https://oss.jtmckj.com/pc/images/pay/arrow-bt.png"
                            />
                            <img
                                v-else
                                class="icon-img"
                                src="https://oss.jtmckj.com/pc/images/pay/arrow-top.png"
                            />
                        </div>
                    </div>
                    <div v-show="!isCollapsed3" class="collapse-content">
                        <!-- 选择物料 -->
                        <el-row style="margin-bottom: 10px;">
                            <el-col :span="12">
                                <el-button
                                    size="small"
                                    class="add-material"
                                    @click="selectMaterial()"
                                >选择物料</el-button>

                                <el-button
                                    size="small"
                                    class="add-material"
                                    @click="saveMaterial()"
                                >补充材料</el-button>
                            </el-col>
                        </el-row>
                        <el-row>
                            <!-- @row-click="checkStoreDetail" -->
                            <el-col :span="24">
                                <el-table
                                    :data="entityObj.applyOrderItemTemps"
                                    :border="true"
                                    style="width: 100%"
                                    highlight-current-row
                                    :show-selection="true"
                                    @row-click="checkStoreDetail"
                                    @selection-change="handleSelectionChange"
                                    ref="tempTable"
                                >
                                    <el-table-column type="selection" width="55"></el-table-column>
                                    <!-- <el-table-column label="物料编码" prop="materialCode" /> -->
                                    <el-table-column
                                        label="物料名称"
                                        prop="materialName"
                                        min-width="140px"
                                    >
                                        <template #default="scope">
                                            <div
                                                v-if="scope.row.materialImages && scope.row.materialImages.length > 0"
                                                style="color: #318cf2;"
                                                @click="handlePreview(scope.row)"
                                            >{{scope.row.materialName}}</div>
                                            <div v-else>{{scope.row.materialName}}</div>
                                        </template>
                                    </el-table-column>
                                    <el-table-column
                                        label="分类"
                                        prop="materialTypeName"
                                        min-width="100px"
                                    />
                                    <el-table-column
                                        label="规格"
                                        prop="materialSpecs"
                                        min-width="140px"
                                    />
                                    <el-table-column label="单位" prop="unitName" min-width="100px" />
                                    <el-table-column label="数量" prop="qty" min-width="100px" />
                                    <el-table-column
                                        label="备注"
                                        prop="remarks"
                                        min-width="200px"
                                        show-overflow-tooltip
                                    />
                                </el-table>
                            </el-col>
                        </el-row>
                    </div>
                </div>
                <div class="collapse-container">
                    <div class="collapse-header" @click="toggleCollapse4">
                        <span>赠送清单</span>
                        <div style="display: flex;align-items: center;">
                            <span class="expand-text">{{ isCollapsed4 ? '展开' : '收起' }}</span>
                            <img
                                v-if="isCollapsed4"
                                class="icon-img"
                                src="https://oss.jtmckj.com/pc/images/pay/arrow-bt.png"
                            />
                            <img
                                v-else
                                class="icon-img"
                                src="https://oss.jtmckj.com/pc/images/pay/arrow-top.png"
                            />
                        </div>
                    </div>
                    <div v-show="!isCollapsed4" class="collapse-content">
                        <!-- 赠送清单 -->
                        <el-row style="margin-bottom: 10px;">
                            <el-col :span="12">
                                <el-button
                                    size="small"
                                    class="add-material"
                                    @click="addMaterial()"
                                >新增物料</el-button>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="24">
                                <el-table
                                    stripe
                                    :data="entityObj.giveOrderItems"
                                    :border="true"
                                    style="width: 100%"
                                    default-expand-all
                                    :row-class-name="setRowClassZs"
                                    @row-click="rowClickZs"
                                >
                                    <el-table-column type="index" min-width="55" fixed />
                                    <!-- <el-table-column
                                        label="物料编码"
                                        prop="materialCode"
                                        min-width="120"
                                    />-->
                                    <el-table-column
                                        label="物料名称"
                                        prop="materialName"
                                        min-width="200"
                                    >
                                        <template #default="scope">
                                            <el-tooltip placement="top" style="width: 80%">
                                                <template #content>{{scope.row.materialCode}}</template>
                                                <div
                                                    v-if="scope.row.materialImages && scope.row.materialImages.length > 0"
                                                    style="color: #318cf2;"
                                                    @click="handlePreview(scope.row.materialImages)"
                                                >{{scope.row.materialName}}</div>
                                                <div v-else>{{scope.row.materialName}}</div>
                                            </el-tooltip>
                                        </template>
                                    </el-table-column>
                                    <!-- <el-table-column
                                        label="分类"
                                        prop="materialTypeName"
                                        min-width="160"
                                    />-->
                                    <el-table-column
                                        label="规格"
                                        prop="materialSpecs"
                                        min-width="140"
                                    />
                                    <el-table-column label="单位" prop="unitName" min-width="60" />
                                    <el-table-column label="供应商" min-width="140" align="center">
                                        <template #default="scope">
                                            <el-select
                                                placeholder="---供应商---"
                                                v-model="scope.row.supplierId"
                                                style="width: 100%"
                                            >
                                                <el-option
                                                    v-for="item in scope.row.suppliers"
                                                    :key="item.orgId"
                                                    :label="item.orgName"
                                                    :value="item.orgId"
                                                />
                                            </el-select>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="配送模式" min-width="140" align="center">
                                        <template #default="scope">
                                            <el-select
                                                placeholder="---采购模式---"
                                                v-model="scope.row.purchaseSaleType"
                                                style="width: 100%"
                                            >
                                                <el-option
                                                    v-for="item in scope.row.suppliers.find(p=>p.orgId==scope.row.supplierId)?.purchaseSaleItems"
                                                    :key="item.purchaseSaleType"
                                                    :label="item.purchaseSaleTypeDesc"
                                                    :value="item.purchaseSaleType"
                                                />
                                            </el-select>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="库存" min-width="60" align="center">
                                        <template
                                            #default="scope"
                                        >{{scope.row.suppliers.find(p=>p.orgId==scope.row.supplierId)?.purchaseSaleItems?.find(p=>p.purchaseSaleType==scope.row.purchaseSaleType)?.stockQty}}</template>
                                    </el-table-column>
                                    <el-table-column
                                        label="销售单价"
                                        min-width="170"
                                        prop="applyPrice"
                                        align="center"
                                    >
                                        <template #default="scope">
                                            <span
                                                v-if="scope.row.purchaseSaleType<20"
                                            >{{scope.row.applyPrice=scope.row.suppliers.find(p=>p.orgId==scope.row.supplierId)?.purchaseSaleItems?.find(p=>p.purchaseSaleType==scope.row.purchaseSaleType)?.applyPrice}}</span>
                                            <el-input-number
                                                v-else
                                                v-model="scope.row.applyPrice"
                                                :precision="0"
                                                :step="1"
                                                :disabled="false"
                                                style="width: 100%"
                                            />
                                        </template>
                                    </el-table-column>
                                    <!-- <el-table-column
                                        label="单价"
                                        min-width="100"
                                        prop="price"
                                        align="center"
                                    >
                                        <template
                                            #default="scope"
                                        >{{scope.row.price=scope.row.suppliers.find(p=>p.orgId==scope.row.supplierId)?.purchaseSaleItems?.find(p=>p.purchaseSaleType==scope.row.purchaseSaleType)?.price}}</template>
                                    </el-table-column>-->
                                    <el-table-column label="赠送数量" prop="qty" min-width="160">
                                        <template #default="scope">
                                            <el-input-number
                                                v-model="scope.row.qty"
                                                step="1"
                                                style="width: 100%"
                                            />
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="审核结果备注" prop="remarks" min-width="120">
                                        <template #default="scope">
                                            <el-input
                                                v-model="scope.row.remarks"
                                                step="1"
                                                style="width: 100%"
                                            />
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="操作" min-width="100" align="center">
                                        <template #default="scope">
                                            <el-button
                                                size="small"
                                                @click="deleteGiveRow(scope,scope.$index)"
                                            >删除</el-button>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </el-col>
                        </el-row>
                    </div>
                </div>
            </el-collapse>

            <!-- <el-row style="margin-top: 10px;">
                <el-col :span="8">
                    <el-form-item label-width="120px" label="采购总数量:">{{totalQty}}</el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="采购总金额:">{{totalAmount}}</el-form-item>
                </el-col>
            </el-row>-->
            <el-row style="margin-top: 20px;">
                <el-col :span="1">
                    <div class="div-label">备注</div>
                </el-col>
                <el-col :span="23">
                    <el-input v-model="entityObj.auditRemarks" type="textarea" :rows="2" />
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <el-row style="margin-top: 20px;" class="font-16">
                <!-- <el-col :span="4">
                    <el-form-item label-width="120px" label="采购总数量:">{{totalQty}}</el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label-width="120px" label="采购总金额:">{{totalAmount}}</el-form-item>
                </el-col>-->
                <el-col :span="16">
                    <el-button @click="handleBeforeClose">取 消</el-button>
                    <el-button
                        v-if="mode != 'show'"
                        type="primary"
                        :loading="isSaveing"
                        @click="returned(1)"
                    >退 回</el-button>
                    <el-button
                        v-if="mode != 'show'"
                        type="primary"
                        :loading="isSaveing"
                        @click="submit(1)"
                    >暂 存</el-button>
                    <el-button
                        v-if="mode != 'show'"
                        type="primary"
                        :loading="isSaveing"
                        @click="submit(2)"
                    >保 存</el-button>
                </el-col>
            </el-row>
        </template>

        <template>
            <el-dialog
                v-model="materialState"
                title="选择商品"
                :width="1000"
                :center="true"
                append-to-body
                style="height: 480px"
            >
                <el-row style="margin-bottom: 45px;">
                    <sc-material-choice
                        ref="scMaterialChoice"
                        :queryType="'material/item-pages'"
                        :queryList="{isPurchasePrice:true}"
                    ></sc-material-choice>
                </el-row>
                <template #footer>
                    <el-button @click="materialState = false">取 消</el-button>
                    <el-button type="primary" :loading="isSaveing" @click="setMaterialChoice">确定</el-button>
                </template>
            </el-dialog>
        </template>
        <!-- 选择物料 -->
        <template>
            <el-dialog
                v-model="selectmaterialState"
                title="选择物料"
                :width="1300"
                :center="true"
                append-to-body
                style="height: 480px"
            >
                <el-row style="margin-bottom: 45px;">
                    <sc-material-choice
                        ref="selectMaterialChoice"
                        :queryType="'delivery-protocol/material-item-pages'"
                        :queryList="{storeId: entityObj.storeId,isAll:true}"
                        :multiple="true"
                    ></sc-material-choice>
                </el-row>
                <template #footer>
                    <el-button @click="selectmaterialState = false">取 消</el-button>
                    <el-button type="primary" :loading="isSaveing" @click="selectMaterialSubmit">确定</el-button>
                </template>
            </el-dialog>
        </template>
        <!-- 选择物料 -->
    </full-screen-dialog>

    <!-- 接单详情 -->
    <receive-detail-dialog
        v-if="receiveDetailSave"
        ref="receiveDetailDialog"
        @splitOrder="splitOrder"
        @saveOrder="saveOrder"
        @getSupplierDesc="getSupplierDesc"
        @closed="receiveDetailSave = false"
    ></receive-detail-dialog>

    <!-- 补充材料 -->
    <material-save-dialog
        v-if="materialSave"
        ref="materialSaveDialog"
        @setTempMaterial="setTempMaterial"
        @closed="materialSave = false"
    ></material-save-dialog>

    <!-- 预览组件 -->
    <el-image-viewer
        v-if="showImage"
        @close="closeViewer"
        :hide-on-click-modal="true"
        :url-list="srcList"
    />
</template>

<script>
import receiveDetailDialog from "./receiveDetail";
import materialSaveDialog from "./materialSave";
import tool from "@/utils/tool";
export default {
    components: {
        receiveDetailDialog,
        materialSaveDialog,
    },
    emits: ["success", "closed"],
    data() {
        return {
            stepStatus: {
                complete:
                    "https://jtmc.oss-cn-hangzhou.aliyuncs.com/public/other/complete.png",
                ing: "https://jtmc.oss-cn-hangzhou.aliyuncs.com/public/other/ing.png",
                wait: "https://jtmc.oss-cn-hangzhou.aliyuncs.com/public/other/not-started.png",
            },
            //预览图片
            previewUrl: [],
            //预览图片列表
            srcList: [],
            showImage: false,
            activeNames: [], // activeNames: ["2", "3"],
            tableRowClassName: "warning-row",
            tableRowClassName1: "success-row",
            mode: "Add",
            titleMap: {
                Add: "新增",
                Edit: "编辑",
                Show: "查看",
            },
            entityObj: {
                purchaseProtocolId: 0,
                purchaseProtocolCode: "",
                purchaseProtocolName: "",
                status: 1,
                crName: "",
                crDate: "",
                supplier: {},
                protocolDate: [],
                purchaseUnityName: "",
                remarks: "",
                protocolFile: "",
                purchaseProtocolItems: [],
                giveOrderItems: [],
            },
            //预览图片
            previewUrl: [],
            //预览图片列表
            srcList: [],
            showImage: false,
            materialSave: false,
            receiveDetailSave: false,
            materialState: false,
            queryList: {},
            visible: false,
            isSaveing: false,
            needSaveFlag: false,
            //验证规则
            rules: {
                purchaseProtocolName: [
                    { required: true, type: "string", message: "请填写" },
                ],
                purchaseUnityName: [
                    { required: true, type: "string", message: "请填写" },
                ],
                supplier: [
                    { required: true, type: "object", message: "请填写" },
                ],
                protocolDate: [
                    { required: true, type: "array", message: "请填写" },
                ],
                crName: [{ required: true, type: "string", message: "请填写" }],
                crDate: [{ required: true, type: "string", message: "请填写" }],
                materialSpecs: [
                    { required: true, type: "string", message: "请填写" },
                ],
                purchaseProtocolItems: [
                    {
                        required: true,
                        type: "array",
                        message: "请填写",
                        trigger: "change",
                    },
                ],
            },
            props: {
                label: "supplierName",
                value: "supplierId",
            },
            materialProps: {
                label: "materialCode",
                value: "materialId",
                items: "materialItems",
            },
            materialTypeTree: [],
            optionsBrand: [],
            optionsUnit: [],
            optionsPurchaseSaleType: [],
            suppliers: [],
            giveSuppliers: [],
            selectmaterialState: false,
            tempOrder: [],
            selectionTempRow: {},
            delTempItems: [],
            isCollapsed: true, // 初始状态为收起
            isCollapsed2: false, // 初始状态为收起
            isCollapsed3: false, // 初始状态为收起
            isCollapsed4: true, // 初始状态为收起
            selected: [], // 当前选中行
            yhSelect: [],
            zsSelect: [],
            itemsData: [],
            querySuppliers: [],
            selectionRows: [],
        };
    },
    computed: {
        totalQty() {
            let applyOrderItems = this.entityObj.applyOrderItems;
            let purchaseQty = 0;
            applyOrderItems?.map((element) => {
                element.purchases?.map((t) => (purchaseQty += t.qty));
            });
            return purchaseQty;
        },
        totalAmount() {
            let applyOrderItems = this.entityObj.applyOrderItems;
            let totalAmount = 0;
            applyOrderItems?.map((element) => {
                console.log(11111);
                console.log(element.purchases);
                element.purchases?.map((t) => {
                    const price =
                        t.suppliers
                            .find((z) => z.orgId == t.supplierId)
                            ?.purchaseSaleItems?.find(
                                (p) => p.purchaseSaleType == t.purchaseSaleType
                            )?.price ?? 0;
                    totalAmount += t.qty * price;
                });
            });
            return totalAmount;
        },
        hasSomeFieldValue() {
            console.log(11111);
            var exists = this.itemsData.some((item) => item.materialQuality);
            console.log("exists", exists);
            return exists;
        },
    },
    methods: {
        selectable() {
            return false;
        },
        //图片预览
        handlePreview(materialImages) {
            if (!materialImages || materialImages.length == 0) {
                return;
            }
            this.previewUrl = materialImages[0]; // 设置当前预览的图片 URL
            this.srcList = materialImages; // 设置预览列表
            this.showImage = true; // 显示 el-image
        },
        closeViewer() {
            console.log(111);
            this.showImage = false;
        },
        checkStoreDetail(row, event) {
            this.$refs.tempTable.clearSelection();
            // 判断是否已经选中
            const isSelected = this.selected.includes(row);
            // 根据当前状态切换选中状态
            if (isSelected) {
                this.$refs.tempTable.toggleRowSelection(row, false); // 取消选中
            } else {
                this.$refs.tempTable.toggleRowSelection(row, true); // 选中行
                this.selectionTempRow = row;
            }
            //this.$refs.tempTable.toggleRowSelection(row);
            //this.selectionTempRow = row;
        },
        handleSelectionChange(selection) {
            this.selected = selection;
            if (selection.length > 1) {
                this.$refs.tempTable.clearSelection();
                this.$refs.tempTable.toggleRowSelection(selection.pop());
            }
            this.selectionTempRow = this.selected[0];
        },
        //获取供应商信息
        getSupplierDesc(purchases, suppliers) {
            // const supplierTotals = suppliers.map((p) => {
            //     let totalQty = 0;
            //     purchases
            //         .filter((t) => t.supplierId == p.orgId)
            //         .map((z) => (totalQty += z.qty));
            //     return {
            //         name: p.orgName,
            //         totalQty: totalQty,
            //     };
            // });
            // //排序
            // const sortedSupplierTotals = supplierTotals.sort(
            //     (a, b) => b.totalQty - a.totalQty
            // );
            return purchases
                .map(
                    (supplier) =>
                        `${supplier.supplierName}/${supplier.totalQty}`
                )
                .join(", ");
        },
        //接单
        opReceive(data) {
            this.receiveDetailSave = true;
            this.$nextTick(() => {
                this.$refs.receiveDetailDialog.setData(data);
                this.$refs.receiveDetailDialog.open("Add");
            });
        },
        toggleCollapse() {
            this.isCollapsed = !this.isCollapsed; // 切换展开/收起状态
        },
        toggleCollapse2() {
            this.isCollapsed2 = !this.isCollapsed2; // 切换展开/收起状态
        },
        toggleCollapse3() {
            this.isCollapsed3 = !this.isCollapsed3; // 切换展开/收起状态
        },
        toggleCollapse4() {
            this.isCollapsed4 = !this.isCollapsed4; // 切换展开/收起状态
        },
        handleBeforeClose() {
            this.$confirm("信息未保存,确定要关闭吗？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    this.visible = false;
                })
                .catch(() => {
                    // 用户点击了取消按钮，不执行关闭
                });
        },
        //显示=
        open(mode = "Add") {
            this.mode = mode;
            this.visible = true;
            return this;
        },
        //表格选择后回调事件
        selectionChange(selection) {
            this.selectionRows = selection;
        },
        //表单提交方法
        submit(status) {
            this.$refs.dialogForm.validate(async (valid) => {
                if (valid) {
                    let data = {
                        applyOrderId: this.entityObj.applyOrderId,
                        remarks: this.entityObj.auditRemarks,
                        status: status,
                        applyOrderItems: [],
                        giveOrderItems: this.entityObj.giveOrderItems,
                    };

                    this.entityObj.applyOrderItems.map((p) => {
                        p.purchases.map((t) => {
                            data.applyOrderItems.push({
                                applyOrderItemTempId: p.applyOrderItemTempId,
                                applyOrderItemId: p.applyOrderItemId,
                                materialTypeId: p.materialTypeId,
                                purchaseSaleType: t.purchaseSaleType,
                                materialId: p.materialId,
                                materialItemId: p.materialItemId,
                                materialCode: p.materialCode,
                                materialName: p.materialName,
                                unitCode: p.unitCode,
                                unitName: p.unitName,
                                price: t.price,
                                applyPrice: t.applyPrice,
                                purchaseTotalAmount: t.purchaseTotalAmount,
                                applyTotalAmount: t.applyTotalAmount,
                                applyQty:p.qty,
                                qty: t.qty,
                                supplierOrgType:t.supplierOrgType,
                                supplierId: t.supplierId,
                                remarks: t.remarks,
                            });
                        });
                    });

                    if (
                        status == 1 &&
                        data.applyOrderItems.length == 0 &&
                        data.giveOrderItems.length == 0
                    ) {
                        this.visible = false;
                        return;
                    }

                    this.isSaveing = true;
                    try {
                        var returnValue =
                            await this.$API.auth.PostProcessApi.post(
                                "purchase-order/create",
                                { ...data }
                            );
                        if (returnValue.status == 200) {
                            this.$message.success("操作成功");
                            this.$emit("fatherMethod");
                            this.isSaveing = false;
                            this.visible = false;
                        } else {
                            this.$message.error("操作失败:" + returnValue.msg);
                            this.isSaveing = false;
                        }
                    } catch (error) {
                        this.loading = false;
                        this.isSaveing = false;
                        return false;
                    }
                }
            });
        },
        //退回
        returned() {
            this.$refs.dialogForm.validate(async (valid) => {
                if (valid) {
                    let data = {
                        applyOrderIds: [this.entityObj.applyOrderId],
                        remarks: this.entityObj.remarks,
                    };

                    try {
                        var returnValue =
                            await this.$API.auth.PostProcessApi.post(
                                "apply-order/returned",
                                { ...data }
                            );
                        if (returnValue.status == 200) {
                            this.$message.success("操作成功");
                            this.$emit("fatherMethod");
                            this.isSaveing = false;
                            this.visible = false;
                        } else {
                            this.$message.error("操作失败:" + returnValue.msg);
                            this.isSaveing = false;
                        }
                    } catch (error) {
                        this.loading = false;
                        this.isSaveing = false;
                        return false;
                    }
                }
            });
        },
        //表单注入数据
        async setData(data) {
            console.log("data1", data);
            //要货明细
            const applyMaterialItemIds = data.applyOrderItems.map(
                (p) => p.materialItemId
            );
            const returnValue = await this.$API.auth.PostProcessApi.post(
                "purchase-protocol/orgs",
                {
                    storeId: data.storeId,
                    orderType: 0,
                    materialItemIds: applyMaterialItemIds,
                    splitMaterials: data.applyOrderItems,
                }
            );
            if (returnValue.status == 200) {
                this.suppliers = [...returnValue.response];
                const _this = this;
                data.applyOrderItems.map(async (p) => {
                    const purchase = _this.suppliers.find(
                        (t) => t.materialItemId == p.materialItemId
                    );
                    //获取所有供应商
                    const suppliers = purchase.purchaseOrgs;
                    //是否有促销活动
                    p.isActivity = purchase.isActivity;
                    p.activityDesc = purchase.activityDesc;
                    p.giveStockDesc = purchase.giveStockDesc;
                    p.suppliers = suppliers;

                    if (p.purchases && p.purchases.length == 0) {
                        //p.purchases = purchase.purchases;
                        p.purchases = [];
                        await this.splitOrder(p);
                    }

                    p.purchases.map((p) => (p.suppliers = suppliers));

                    p.supplierTotals = p.purchases
                        .map(
                            (supplier) =>
                                `${supplier.supplierName}/${supplier.qty}`
                        )
                        .join(", ");
                    p.applyTotalAmount = p.purchases.reduce(
                        (sum, p) => sum + p.applyTotalAmount,
                        0
                    );
                    p.purchaseTotalAmount = p.purchases.reduce(
                        (sum, p) => sum + p.purchaseTotalAmount,
                        0
                    );
                    // p.purchases.map((t) => {
                    //     t.suppliers = suppliers;
                    // });
                });
            }

            //赠送
            data.giveOrderItems = data.giveOrderItems.filter(
                (p) => p.giveOrderStatus == 0
            );
            const giveMaterialItemIds = data.giveOrderItems.map(
                (p) => p.materialItemId
            );
            const returnValue1 = await this.$API.auth.PostProcessApi.post(
                "purchase-protocol/purchase-suppliers",
                {
                    storeId: data.storeId,
                    orderType: 1,
                    materialItemIds: giveMaterialItemIds,
                }
            );
            if (returnValue1.status == 200) {
                this.giveSuppliers = [...returnValue1.response];

                data.giveOrderItems.map((p) => {
                    const purchase = this.giveSuppliers.find(
                        (t) => t.materialItemId == p.materialItemId
                    );
                    //获取所有供应商
                    const suppliers = purchase.purchaseOrgs;
                    p.suppliers = suppliers;
                });
            }

            this.entityObj = {
                ...data,
                applyOrderItems: [
                    ...data.applyOrderItems.filter((p) => p.receiveStatus == 0),
                ],
                //giveOrderItems: [],
            };
            console.log("entityObjs", this.entityObj);
            this.getSuppliers();
            //暂存的临时物料
            this.delTempItems = data.delApplyOrderItemTemps.filter((p) => p.receiveStatus == 0);

            this.activeNames = []; // this.activeNames = ["2", "3"];

            this.queryList = {};
            this.handleSearch();
        },
        //拆单
        async splitOrder(data) {
            debugger;
            const suppliers = this.suppliers.find(
                (t) => t.materialItemId == data.materialItemId
            ).purchaseOrgs;
            const purchaseSaleItems =
                suppliers && suppliers.length > 0
                    ? suppliers[0].purchaseSaleItems
                    : null;
            const applyPrice = purchaseSaleItems
                ? purchaseSaleItems[0]?.applyPrice
                : 0.0;
            const purchasePrice = purchaseSaleItems
                ? purchaseSaleItems[0]?.price
                : 0.0;

            let totalQty = 0;
            console.log(data.purchases);
            data.purchases.map((p) => (totalQty += p.qty));
            data.purchases.push({
                suppliers: suppliers,
                supplierOrgType:suppliers && suppliers.length > 0? suppliers[0].orgType: null,
                supplierId:suppliers && suppliers.length > 0? suppliers[0].orgId: null,
                supplierName:suppliers && suppliers.length > 0? suppliers[0].orgName: null,
                qty: data.qty - totalQty,
                price: purchasePrice,
                applyPrice: applyPrice,
                applyTotalAmount: (data.qty - totalQty) * applyPrice,
                purchaseTotalAmount: (data.qty - totalQty) * purchasePrice,
                optionsPurchaseSaleType: purchaseSaleItems,
                purchaseSaleType: suppliers && suppliers.length > 0? suppliers[0].purchaseSaleType: null,
                stockQty: purchaseSaleItems
                    ? purchaseSaleItems[0]?.stockQty
                    : null,
            });
        },
        async saveOrder(data) {
            console.log(data);
            let applyOrderItem = this.entityObj.applyOrderItems.find(
                (p) => p.applyOrderItemId == data.applyOrderItemId
            );
            applyOrderItem.purchases = [...data.purchases];
            applyOrderItem.supplierTotals = applyOrderItem.purchases
                .map((supplier) => `${supplier.supplierName}/${supplier.qty}`)
                .join(", ");
            applyOrderItem.applyTotalAmount = applyOrderItem.purchases.reduce(
                (sum, p) => sum + p.applyTotalAmount,
                0
            );
            applyOrderItem.purchaseTotalAmount =
                applyOrderItem.purchases.reduce(
                    (sum, p) => sum + p.purchaseTotalAmount,
                    0
                );
        },
        handleQuantityChange(row, data) {
            let totalQty = 0;
            data.purchases.forEach((p) => (totalQty += p.qty));
            if (row.qty < 0) {
                this.$nextTick(() => {
                    row.qty = 0;
                });
                this.$message.error("采购数量不能小于0");
            }

            if (totalQty > data.qty) {
                this.$nextTick(() => {
                    row.qty -= totalQty - data.qty;
                });
                this.$message.error("采购数量不能大于要货数量");
            }
        },
        getSummaries(param) {
            const { columns, data } = param;
            const sums = [];
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = "合计";
                    return;
                }
                const values = data.map((item) =>
                    Number(item[column.property])
                );

                if (
                    column.property == "qty" ||
                    column.property == "totalAmount"
                ) {
                    if (!values.every((item) => isNaN(item))) {
                        const total = values.reduce((a, b) => a + b, 0);
                        sums[index] = total;
                    }
                }
            });
            return sums;
        },
        async initOptions() {
            try {
                var returnValue = await this.$API.auth.PostProcessApi.post(
                    "base-dictionary/options",
                    { Codes: ["PurchaseSaleType"] }
                );
                if (returnValue.status == 200) {
                    this.optionsPurchaseSaleType = returnValue.response.find(
                        (p) => p.code == "PurchaseSaleType"
                    ).optionsDetails;
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            } catch (error) {
                this.loading = false;
                return false;
            }
        },
        async getSuppliers() {
            try {
                const returnValue = await this.$API.auth.GetProcessApi.get(
                    `store/${this.entityObj.storeId}/suppliers`,
                    {}
                );
                if (returnValue.status == 200) {
                    this.querySuppliers = [...returnValue.response.suppliers];
                }
            } catch (error) {
                this.loading = false;
                return false;
            }
        },
        addMaterial() {
            this.materialState = true;
        },
        //选中物料
        selectMaterial() {
            if (
                this.selectionTempRow &&
                this.selectionTempRow.applyOrderItemTempId > 0
            ) {
                this.selectmaterialState = true;
                this.$nextTick(() => {
                    this.$refs.selectMaterialChoice.opBindData();
                });
            } else {
                this.$message.error("请选中一行，再点击选择物料按钮");
            }
        },
        saveMaterial() {
            if (
                this.selectionTempRow &&
                this.selectionTempRow.applyOrderItemTempId > 0
            ) {
                this.materialSave = true;
                this.$nextTick(() => {
                    this.$refs.materialSaveDialog.open("Edit").setData({
                        storeId: this.entityObj.storeId,
                        ...this.selectionTempRow,
                    });
                });
            } else {
                this.$message.error("请选中一行，再点击选择物料按钮");
            }
        },
        //选择物料确认
        async selectMaterialSubmit() {
            let materials = this.$refs.selectMaterialChoice.selectionRows;
            await this.setTempMaterial(materials);
        },
        //设置临时物料
        async setTempMaterial(materials) {
            console.log("materials1", materials);
            if (materials.length > 1) {
                this.$message.error("请选择一条物料");
                return;
            }
            if (materials.length == 0) {
                this.selectmaterialState = false;
                return;
            }
            const materialItemIds = materials.map((p) => p.materialItemId);

            const returnValue = await this.$API.auth.PostProcessApi.post(
                "purchase-protocol/orgs",
                {
                    storeId: this.entityObj.storeId,
                    orderType: 0,
                    materialItemIds: materialItemIds,
                }
            );
            if (returnValue.status == 200) {
                if (!this.suppliers) {
                    this.suppliers = [];
                }
                this.suppliers.push(...returnValue.response);
                materials.map((p) => {
                    const purchase = this.suppliers.find(
                        (t) => t.materialItemId == p.materialItemId
                    );
                    //获取所有供应商
                    const suppliers = purchase.purchaseOrgs;
                    //默认供应商
                    const supplier =
                        suppliers.find(
                            (p) => p.supplierId == purchase.supplierId
                        ) ?? suppliers[0];

                    let applyOrderItem =  {
                        purchases: [
                            {
                                suppliers: suppliers,
                                supplierOrgType:supplier?.orgType,
                                supplierId: supplier?.orgId,
                                supplierName: supplier?.orgName,
                                optionsPurchaseSaleType:
                                    supplier?.purchaseSaleItems,
                                purchaseSaleType:
                                    supplier?.purchaseSaleItems[0]
                                        ?.purchaseSaleType,
                                stockQty:
                                    supplier?.purchaseSaleItems[0]?.stockQty,
                                price: supplier?.purchaseSaleItems[0]?.price,
                                applyPrice:supplier?.purchaseSaleItems[0]?.applyPrice,
                                applyTotalAmount:supplier?.purchaseSaleItems[0]?.applyPrice*this.selectionTempRow.qty,
                                purchaseTotalAmount:supplier?.purchaseSaleItems[0]?.price*this.selectionTempRow.qty,
                                totalAmount:this.selectionTempRow.qty * supplier?.price,
                                qty: this.selectionTempRow.qty,
                            },
                        ],
                        giveStockDesc: purchase.giveStockDesc,
                        isActivity: purchase.isActivity,
                        materialId: p.materialId,
                        materialCode: p.materialCode,
                        materialName: p.materialName,
                        materialSpecs: p.materialSpecs,
                        materialTypeId: p.materialTypeId,
                        materialTypeName: p.materialTypeName,
                        unitCode: p.unitCode,
                        unitName: p.unitName,
                        materialItemId: p.materialItemId,
                        price: p.price,
                        qty: this.selectionTempRow.qty,
                        totalAmount: this.selectionTempRow.qty * p.price,
                        applyOrderItemId:
                            this.selectionTempRow.applyOrderItemId,
                        applyOrderItemTempId:
                            this.selectionTempRow.applyOrderItemTempId,
                        applyMaterialImages:
                            this.selectionTempRow.applyMaterialImages,
                    }  

                    applyOrderItem.supplierTotals = applyOrderItem.purchases
                        .map((supplier) => `${supplier.supplierName}/${supplier.qty}`)
                        .join(", ");
                    applyOrderItem.applyTotalAmount = applyOrderItem.purchases.reduce(
                        (sum, p) => sum + p.applyTotalAmount,
                        0
                    );
                    applyOrderItem.purchaseTotalAmount =
                        applyOrderItem.purchases.reduce(
                            (sum, p) => sum + p.purchaseTotalAmount,
                            0
                        );

                    this.entityObj.applyOrderItems.push(applyOrderItem);
                });
            }
            
            

            this.entityObj.applyOrderItemTemps =
                this.entityObj.applyOrderItemTemps.filter(
                    (item) =>
                        item.applyOrderItemTempId !==
                        this.selectionTempRow.applyOrderItemTempId
                );
            //添加临时物料
            this.delTempItems.push(this.selectionTempRow);
            this.selectmaterialState = false;
        },
        deleteRow(data, index) {
            data.purchases.splice(index, 1);
        },
        delOrder(data, index) {
            const delTempItem = this.delTempItems.find(
                (p) => p.applyOrderItemTempId == data.applyOrderItemTempId
            );
            this.entityObj.applyOrderItemTemps.push(delTempItem);
            this.entityObj.applyOrderItems.splice(index, 1);
        },
        deleteGiveRow(data, index) {
            this.entityObj.giveOrderItems.splice(index, 1);
        },
        async setMaterialChoice() {
            let materials = this.$refs.scMaterialChoice.selectionRows;
            const materialItemIds = materials.map((p) => p.materialItemId);
            const returnValue = await this.$API.auth.PostProcessApi.post(
                "purchase-protocol/purchase-suppliers",
                {
                    storeId: this.entityObj.storeId,
                    orderType: 1,
                    materialItemIds: materialItemIds,
                }
            );
            if (returnValue.status == 200) {
                if (!this.suppliers) {
                    this.suppliers = [];
                }
                this.giveSuppliers.push(...returnValue.response);
                materials.map((p) => {
                    const suppliers = this.giveSuppliers.find(
                        (t) => t.materialItemId == p.materialItemId
                    ).purchaseOrgs;
                    this.entityObj.giveOrderItems.push({
                        suppliers: suppliers,
                        supplierId:
                            suppliers && suppliers.length > 0
                                ? suppliers[0].orgId
                                : null,
                        optionsPurchaseSaleType:
                            suppliers && suppliers.length > 0
                                ? suppliers[0].purchaseSaleItems
                                : null,
                        purchaseSaleType:
                            suppliers && suppliers.length > 0
                                ? suppliers[0].purchaseSaleItems[0]
                                      ?.purchaseSaleType
                                : null,
                        stockQty:
                            suppliers &&
                            suppliers.length > 0 &&
                            suppliers[0].purchaseSaleItems[0].length > 0
                                ? suppliers[0].purchaseSaleItems[0]?.stockQty
                                : null,
                        applyPrice:
                            suppliers &&
                            suppliers.length > 0 &&
                            suppliers[0].purchaseSaleItems[0].length > 0
                                ? suppliers[0].purchaseSaleItems[0]?.applyPrice
                                : 0,
                        price:
                            suppliers &&
                            suppliers.length > 0 &&
                            suppliers[0].purchaseSaleItems[0].length > 0
                                ? suppliers[0].purchaseSaleItems[0]?.price
                                : 0,
                        materialId: p.materialId,
                        materialCode: p.materialCode,
                        materialName: p.materialName,
                        materialSpecs: p.materialSpecs,
                        materialTypeId: p.materialTypeId,
                        materialTypeName: p.materialTypeName,
                        unitCode: p.unitCode,
                        unitName: p.unitName,
                        remarks: "同意",
                        materialItemId: p.materialItemId,
                        qty: 1,
                    });
                });
            }

            console.log(this.entityObj.giveOrderItems);
            this.materialState = false;
        },
        formatDate(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, "0");
            const day = String(date.getDate()).padStart(2, "0");
            const hours = String(date.getHours()).padStart(2, "0");
            const minutes = String(date.getMinutes()).padStart(2, "0");
            const seconds = String(date.getSeconds()).padStart(2, "0");

            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        },
        // 点击行 要货清单
        rowClickYh(row) {
            console.log(row);
            this.yhSelect = [row];
        },
        // 点击行 赠送清单
        rowClickZs(row) {
            console.log(row);
            this.zsSelect = [row];
        },
        // 动态样式 选中效果
        setRowClass({ row }) {
            if (this.yhSelect.includes(row)) {
                return "selected-row-color";
            }
            return "warning-row";
        },
        setRowClassZs({ row }) {
            if (this.zsSelect.includes(row)) {
                return "selected-row-color";
            }
            return "warning-row";
        },
        resetSearch() {
            this.queryList = {};
        },
        handleSearch() {
            this.itemsData = this.entityObj.applyOrderItems;
            if (this.queryList.supplierId) {
                this.itemsData = this.itemsData.filter((person) =>
                    person.purchases.some(
                        (purchase) =>
                            purchase.supplierId == this.queryList.supplierId
                    )
                );
            }
        },
        //排序
        handleSortChange(sort) {
            console.log("排序字段:", sort.prop);
            console.log("排序方式:", sort.order);

            this.itemsData.sort((a, b) => {
                if (sort.order === "ascending") {
                    return a[sort.prop] > b[sort.prop] ? 1 : -1;
                } else if (sort.order === "descending") {
                    return a[sort.prop] < b[sort.prop] ? 1 : -1;
                }
                return 0;
            });
        },
        //修改临时物料要货数量
        handleApplyQty(row,applyIndex){
            let applyOrderItem=this.itemsData[applyIndex];
            if(applyOrderItem&&applyOrderItem.purchases){
                const splitQty = applyOrderItem.purchases.slice(1).reduce((sum, item) => sum + item.qty, 0);
                applyOrderItem.purchases[0].qty=row.qty-splitQty;
            }

            applyOrderItem.supplierTotals = applyOrderItem.purchases
                .map((supplier) => `${supplier.supplierName}/${supplier.qty}`)
                .join(", ");
            applyOrderItem.applyTotalAmount = applyOrderItem.purchases.reduce(
                (sum, p) => sum + p.qty*p.applyPrice,
                0
            );
            applyOrderItem.purchaseTotalAmount =
                applyOrderItem.purchases.reduce(
                    (sum, p) => sum +p.qty*p.price, 
                    0
                );
        },
    },
    async mounted() {
        this.entityObj.purchaseUnityName = tool.data.get("USER_INFO").OrgName;
        this.entityObj.crName = tool.data.get("USER_INFO").Name;
        this.entityObj.crDate = this.formatDate(new Date());
        await this.initOptions();
    },
};
</script>

<style scoped lang="scss">
/* 当表格行处于悬停状态时改变背景颜色 */
::v-deep .el-table .el-table__row:hover {
    background-color: #dae8f7;
}
::v-deep .el-table .el-table__row .warning-row .hover-row td {
    background-color: #dae8f7;
}
::v-deep .el-table__row .warning-row:hover {
    background-color: #dae8f7;
}
::v-deep .el-table__body .el-table__row--striped.hover-row td {
    background-color: #dae8f7 !important;
}
::v-deep .el-table--enable-row-transition .el-table__body td.el-table__cell {
    background-color: #f5f7fa;
    transition: none;
}
::v-deep .el-table__body tr.hover-row > td.el-table__cell {
    background-color: #dae8f7;
    transition: none;
}
::v-deep .basic-table .el-table .el-table__cell.is-center {
    // background-color: transparent;
}
::v-deep {
    .el-table .selected-row-color {
        background-color: #b8dcff !important;
    }
    .el-table--enable-row-hover
        .el-table__body
        tr.selected-row-color:hover
        > td {
        background-color: #b8dcff !important;
    }
    .el-table__body-wrapper
        .el-table__body
        tr.selected-row-color.hover-row
        > td {
        background-color: #b8dcff !important;
    }
    .el-table__fixed-body-wrapper
        .el-table__body
        tr.selected-row-color.hover-row
        > td {
        background-color: #b8dcff !important;
    }
    .el-table__body-wrapper
        .el-table__body
        tr.selected-row-color.hover-row
        > .el-table__row--striped {
        background-color: #b8dcff !important;
    }
    .el-table--enable-row-transition .el-table__body td.el-table__cell {
        background-color: transparent;
        transition: none;
    }
    .el-table__body tr.hover-row > td.el-table__cell {
        background-color: transparent;
        transition: none;
    }
    .el-table__body .el-table__row--striped.selected-row-color td {
        background-color: #b8dcff !important;
    }
}

.el-table .warning-row {
    --el-table-tr-bg-color: var(--el-color-warning-light-9);
}
.el-table .success-row {
    --el-table-tr-bg-color: var(--el-color-success-light-9);
}
.el-form-item {
    margin-bottom: 8px !important;
}
.div-label {
    font-size: 16px;
    text-align: left;
    font-family: Microsoft YaHei;
    font-weight: bold;
    font-size: 16px;
    color: #666666;
    width: 60px;
}

.steps-view {
    height: 70x;
    margin-top: -15px;
    margin-bottom: 8px;
}
.steps-view-line {
    height: 32px;
    display: flex;
    flex-direction: row;
    align-items: center;
}
.steps-line-blue {
    height: 6px;
    width: 20%;
    background-color: #308bf2;
    opacity: 0.2;
}
.steps-line-ash {
    height: 6px;
    width: 20%;
    background-color: #e6e6e6;
}
.steps-view-text {
    height: 38px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
}
.steps-uning {
    width: 272px;
    text-align: center;
    color: #999999;
    font-family: Microsoft YaHei;
    font-weight: 400;
    font-size: 14px;
}
.steps-ing {
    width: 272px;
    text-align: center;
    color: #308bf2;
    font-family: Microsoft YaHei;
    font-weight: 400;
    font-size: 14px;
}
.w-119 {
    width: 119px;
}
.w-32 {
    width: 32px;
}
.w-24-4 {
    width: 24px;
    margin: 4px;
}
.w-32-4 {
    width: 32px;
    padding: 4px;
}
.add-material {
    width: 80px;
    height: 28px;
    font-family: Microsoft YaHei;
    font-weight: 400;
    font-size: 14px;
    width: 80px;
    background: #ffffff;
    border-radius: 4px;
    border: 1px solid #e6e6e6;
}

.collapse-container {
    border-top: 1px solid #f6f6f6;
    border-bottom: 1px solid #f6f6f6;
    padding: 10px 10px 10px 0;
    margin-bottom: 10px;
}

.collapse-header {
    display: flex;
    justify-content: space-between;
    cursor: pointer;
    padding: 5px;
    padding-left: 0;
    font-weight: bold;
    font-size: 16px;
}

.expand-text {
    color: #308bf2; /* Element UI 的蓝色 */
    font-size: 14px;
}
.icon-img {
    width: 16px;
    height: 10px;
    margin-left: 5px;
}
.collapse-content {
    padding: 10px;
}

.collapse-content1 {
    padding: 10px;
    background: #f2f2f2;
}

/* 过渡动画样式 */
.fade-enter-active,
.fade-leave-active {
    transition: opacity 0.6s ease;
}

.fade-enter, .fade-leave-to /* .fade-leave-active in <2.1.8 */ {
    opacity: 0;
}
::v-deep(.subtable .el-table__header th) {
    background-color: #e6e6e6 !important;
}
::v-deep(.subtable .el-table__expanded-cell) {
    background-color: #f5f7fa !important;
}
::v-deep(.custom-table) {
    margin: 0 auto;
    width: 80% !important;
}

::v-deep(.custom-table .el-table__header th) {
    background-color: #ffffff !important;
}
::v-deep(.custom-table .el-table__cell) {
    background-color: #ffffff !important;
}
::v-deep(.custom-table .el-table__cell.is-leaf) {
    border: none !important;
}
</style>

